// shm_demo.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_KEY 1234
#define BUF_SIZE 1024

int main() {
    int shmid = shmget(SHM_KEY, BUF_SIZE, IPC_CREAT | 0666);
    if (shmid == -1) {
        perror("shmget");
        exit(1);
    }

    char *data = (char *)shmat(shmid, NULL, 0);
    if (data == (char *)-1) {
        perror("shmat");
        exit(1);
    }

    pid_t pid = fork();
    if (pid == 0) { // 子进程
        sprintf(data, "Hello from child");
        sleep(1);
        shmdt(data);
    } else { // 父进程
        sleep(1);
        printf("Parent received: %s\n", data);
        shmdt(data);
        shmctl(shmid, IPC_RMID, NULL); // 删除共享内存
    }

    return 0;
}
